using System;
using System.Collections.Generic;
using NHibernate;
using Tools.Common.UnitOfWork.Contracts;
using Tools.Domain.Specifications;
using Web.App.Infrastructure.ObjectStore.Contracts;

namespace Web.App.Infrastructure.ObjectStore.Implementation
{
    public class NHBasedObjectStore : IObjectStoreRepository
    {
        private IUoWContainer uoWContainer;
        private ISession session;

        public NHBasedObjectStore(IUoWContainer uoWContainer)
        {
            this.uoWContainer = uoWContainer;
            session = uoWContainer.Current.CurrentSession as ISession;
        }

        public void Add(ObjectStoreItem item)
        {
            session.Save(item);
            session.Flush();
        }

        public ObjectStoreItem Add(object data, string description)
        {
            var newObjectStoreItem = new ObjectStoreItem(Guid.NewGuid(), data, DateTime.Now, data.GetType(), description);
            Add(newObjectStoreItem);
            return newObjectStoreItem;
        }

        public void Update(Guid id, object data)
        {
            var objectStoreItem = session.Get<ObjectStoreItem>(id);
            objectStoreItem.Data = data;
            objectStoreItem.AddedAt = DateTime.Now.AddSeconds(1);
            objectStoreItem.Description = objectStoreItem.Description;
            session.Update(objectStoreItem, id);
            session.Flush();


            //var newObjectStoreItem = new ObjectStoreItem(id, data, DateTime.Now, data.GetType(),
            //                                             objectStoreItem.Description);
            //Remove(objectStoreItem);
            //Add(objectStoreItem);
        }

        public void Remove(ObjectStoreItem item)
        {
            session.Delete(item);
            session.Flush();
        }

        public void Remove(Guid id)
        {
            var objectStoreItem = session.Get<ObjectStoreItem>(id);
            Remove(objectStoreItem);
        }

        public IEnumerable<ObjectStoreItem> Find(Func<ObjectStoreItem, bool> predicate)
        {
            throw new System.NotImplementedException();
        }

        public IEnumerable<ObjectStoreItem> Find(ISpecification<ObjectStoreItem> predicate)
        {
            throw new System.NotImplementedException();
        }

        public ObjectStoreItem Find(Guid id)
        {
            return session.Get<ObjectStoreItem>(id);
        }
    }
}